package com.sheng.project.study.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author liusheng
 * @date 2023/06/29
 */
public class CostTimeProxy implements MethodInterceptor {

    private Object target;

    public CostTimeProxy(Object target) {
        this.target = target;
    }

    public static <T> T createProxy(T t) {
        CostTimeProxy costTimeProxy = new CostTimeProxy(t);
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(t.getClass());
        enhancer.setCallback(costTimeProxy);
        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        long start = System.nanoTime();
        Object result = methodProxy.invokeSuper(o, objects);
        long end = System.nanoTime();
        System.out.println("方法 " + method.getDeclaringClass().getName() + "." + method.getName() + "() 耗时：" + (end - start));
        return result;
    }
}
